using System.Collections.Generic;
using System.Data;
using System.Linq;
using Magiq.Behaviors;
using Magiq.Insert;

namespace Magiq.Databases.Insert
{
    public class DatabaseInsertBehavior<TSource, TDestination, TNew> : DefaultBehavior, IDatabaseInsertBehavior<TSource, TDestination, TNew>
        where TDestination : class
        where TNew : class 
    {
        private IInsert<TSource, TDestination, TNew> insert;

        public void Initialize(IDatabaseAdapter databaseAdapter, IInsert<TSource, TDestination, TNew> insert)
        {
            this.insert = insert;
            DatabaseAdapter = databaseAdapter;
        }

        protected IDatabaseAdapter DatabaseAdapter { get; private set; }

        public IEnumerable<DatabaseInsert<TSource>> BuildDatabaseInserts()
        {
            return DatabaseAdapter.BuildDatabaseInserts(insert);
        }

        public IDbCommand BuildCommand(DatabaseInsert<TSource> insert)
        {
            var builder = new InsertCommandBuilder(typeof(TNew), insert.DatabaseAdapter, (IQueryable)insert.Source, insert.ColumnAssignments);
            return builder.GetCommand();
        }

        protected virtual IEnumerable<InsertColumnsAssignment> CustomAssignments(
            IInsert<TSource, TDestination, TNew> insert)
        {
            yield break;
        }
    }
}